var listColumns = [[
    {field: "id", checkbox: true},
    {field: "userName", title: "登录名", align: "center", width: 100},
    {field: "displayName", title: "姓名", align: "center", width: 120},
    {field: "roleName", title: "角色", align: "center", width: 120},
    {field: "roleId", title: "角色", align: "center", hidden:'true', width: 120},
    {field: "telphone", title: "手机号", align: "center", width: 120},
    {field: "email", title: "邮箱", align: "center", width: 140},
    {field: "description", title: "描述", align: "center", width: 100},
    {field: "rankId", title: "是否属于组", align: "center", width: 90,formatter:function(value,rowData){
        switch(value){
            case "1": return "是";
            case "0": return "否";
        }
    }},
    {field: "addressId", title: "地址", align: "center", width: 90,formatter:function(value,rowData){
        switch(value){
            case "01": return "兆丰";
            case "02": return "科汇";
            case "03": return "百丽";
            case "04": return "其他";
            case "05": return "杨浦";
        }
    }},
    {field: "enabled", title: "是否可用", align: "center", width: 120,formatter: function (value,rowData,index) {
        switch (value){
            case true: return "可用";
            case false: return "不可用";
        }
    }},
    {field: "extension", title: "分机号", align: "center", width: 50},
    {field: "skillDesc", title: "技能组", align: "center", width: 100},
    /*{field: "creator", title: "创建人ID", align: "center", width: 120,formatter: function (value) {
        if(value == 'QYWX'){
            return "企业微信";
        }
        return value;
    }},*/
    {field: "createTime", title: "创建时间", align: "center", width: 140},
    {
        field: "handle", title: "操作", align: "center", width: 120, formatter: function (value, rowData,index) {
        return '<a class="layui-btn layui-btn-xs"  onclick="editData('+index+')">编辑</a>' +
            '<a class="layui-btn layui-btn-xs layui-btn-danger" onclick="deleteData('+rowData.id+')" style="text-decoration: none">删除</a>'
    }
    }
]];

layui.config({
    base: "../static/agent-ui/js/"
});

$.fn.toJSON = function () {
    var o = {};
    var a = this.serializeArray();
    $.each(a, function () {
        var name = this.name;
        var value = this.value;
        var paths = this.name.split(".");
        var len = paths.length;
        var obj = o;
        $.each(paths, function (i, e) {
            if (i == len - 1) {
                if (obj[e]) {
                    if (!obj[e].push) {
                        obj[e] = [obj[e]];
                    }
                    obj[e].push(value || '');
                } else {
                    obj[e] = value || '';
                }
            } else {
                if (!obj[e]) {
                    obj[e] = {};
                }
            }
            obj = o[e];
        });
    });
    return o;
};

layui.use(["laypage", "layer", "validator", "tools", "form", "select", "laydate"], function () {
    var form = layui.form;
    var date = layui.laydate;
    date.render({
        elem: '#ringTime',
        type: 'datetime',
        range: true
    });


    var layer=layui.layer;

    $(function () {
        $('#list').datagrid({
            columns: listColumns,
            fitColumns: false,
            fit: true,
            singleSelect: true,
            pagination: true,
            pageSize: 30,
            pageList: [30, 50, 100, 1000],
            toolbar: '#receivedListHeader',
            method: 'get',
            url: ctx +'/user/list',
            onLoadSuccess: function () {
                getRole(function(optionString){
                    $("#search_form").find('select[name=roleId]').empty();
                    $("#search_form").find('select[name=roleId]').append(optionString);
                    var form = layui.form;
                    form.render('select');
                });


            }
        });
    });

    $('#search_submit').on('click', function () {
        $('#list').datagrid('load', $('#search_form').toJSON());
    });

    $("#syncUser").on("click",function(){
        layer.confirm("是否同步", {
            btn: ['是','否'] //按钮
        }, function(index){
            $.ajax({
                url:ctx+'/schedule/user',
                type : 'GET',
                dataType: 'json',
                success:function (result) {
                   if(result.code =='0'){
                       layer.close(index);
                       $('#list').datagrid('reload');
                   }else{
                       layer.open({
                           title: '报错了'
                           ,content: result.msg
                       });
                   }
                },
                error:function (result) {
                    layer.open({
                        title: '报错了'
                        ,content: '报错了 请联系管理员'
                    });
                }
            });
        },function(index){
            layer.close(index);
        });
    });

    $("#addData").on("click", function(){
        /* 再弹出添加界面 */
        layer.open({
            type:1,
            title:"添加用户",
            skin:"myclass",
            area:["50%","85%"],
            content:$("#add").html(),
            success:function (layero,index) {
                layero.addClass('layui-form');
                layero.find('.layui-layer-btn0').attr('lay-filter', 'fromContent').attr('lay-submit', '');//将按钮弄成能提交的
                getRole(function (optionString) {
                    $(layero).find('select[name=roleId]').empty();
                    $(layero).find('select[name=roleId]').append(optionString);
                    form.render('select'); //刷新select选择框渲染
                });


            },
            btn:['提交','关闭'],
            yes:function (index,layero) {
                form.on('submit(fromContent)', function (data) {
                    add(index,'1',layero)
                });
            },
            btn2:function (index,layero) {
                layer.close(index);
            }
        });

    });
});

var cache_role;
function getRole(callback) {
    if(cache_role != null ){
        if(callback !=null){
            callback(cache_role);
        }
    }else {
        $.ajax({
            url: ctx + '/role/list',
            type : 'GET',
            dataType: 'json',
            success: function (result) {
                var roleList = result.data;
                var optionString = "<option value=''>请选择...</option>";
                roleList.forEach((role,index) =>{
                    optionString += "<option value = '"+role.id+"'>"+role.roleName+"</option>";
            });
                cache_role = optionString;
                if(callback !=null){
                    callback(optionString);
                }

            },
            error: function (result) {
                layer.open({
                    title: '报错了'
                    ,content: '获取角色失败'
                });
            }
        });
    }
}
function add(index,status,layero) {
    $.ajax({
        url:ctx+'/user/insert',
        type : 'POST',
        data:$(layero).find("form[id=add_form]").toJSON(),
        success:function (result) {
            var layer = layui.layer;
            var json = JSON.parse(result);
            if(json.code=='0'){
                layer.close(index);
                $('#list').datagrid('reload');
            }else{
                layer.open({
                    title: '报错了'
                    ,content: json.msg
                });
            }

        },
        error:function (result) {
            var json = JSON.parse(result);
            var layer = layui.layer;
            layer.open({
                title: '报错了'
                ,content: '新增失败'
            });

        }
    });
}



function deleteData(id) {
    layer.confirm('是否确认删除！', {
        btn: ['删除','关闭'] //按钮
    }, function(index){
        $.ajax({
            url:ctx+'/user/delete/'+id,
            type : 'GET',
            success: function(result){
                var layer = layui.layer;
                var json = JSON.parse(result);
                if(json.code=='0'){
                    layer.close(index);
                    $('#list').datagrid('reload');
                }else{
                    layer.open({
                        title: '报错了'
                        ,content: json.msg
                    });
                }
            },
            error: function(result){
                var json = JSON.parse(result);
                var layer = layui.layer;
                layer.open({
                    title: '报错了'
                    ,content: '删除失败'
                });
            }
        });
    }, function(index){
        layer.close(index);
    });
}

// 编辑
function  editData(index) {
    var rows = $('#list').datagrid('getRows');
    var json = rows[index];
    var form = layui.form;
    layer.open({
        type:1,
        title:"编辑",
        skin:"myclass",
        area:["50%","350px"],
        content:$("#add").html(),
        success:function (layero,index) {
            layero.addClass('layui-form');
            layero.find('.layui-layer-btn0').attr('lay-filter', 'fromContent').attr('lay-submit', '');//将按钮弄成能提交的
            getRole(function (optionString) {
                $(layero).find('select[name=roleId]').empty();
                $(layero).find('select[name=roleId]').append(optionString);

                $(layero).find('input[name=displayName]').val(json.displayName);
                $(layero).find('select[name=roleId]').val(json.roleId);
                $(layero).find('select[name=rankId]').val(json.rankId);// 是否属于组
                $(layero).find('input[name=userName]').val(json.userName);
                $(layero).find('input[name=telphone]').val(json.telphone);
                $(layero).find('select[name=enabled]').val(json.enabled==true?"true":"false");
                $(layero).find('select[name=addressId]').val(json.addressId);
                $(layero).find('input[name=description]').val(json.description);
                $(layero).find('input[name=skillDesc]').val(json.skillDesc);// 技能组
                $(layero).find('input[name=extension]').val(json.extension);// 分机号
                $(layero).find('input[name=email]').val(json.email);// 邮箱
                form.render(); //刷新select选择框渲染
            });

        },
        btn:['提交','关闭'],
        yes:function (index,layero) {
            form.on('submit(fromContent)', function (data) {
                update(index,json.id,layero)
            });
        },
        btn2:function (index,layero) {
            layer.close(index);
        }
    });
}
function update(index,id,layero) {
    $.ajax({
        url:ctx+'/user/update/'+id,
        type : 'POST',
        data:$(layero).find("form[id=add_form]").toJSON(),
        success:function (result) {
            var layer = layui.layer;
            var json = JSON.parse(result);
            if(json.code=='0'){
                layer.close(index);
                $('#list').datagrid('reload');
            }else{
                layer.open({
                    title: '报错了'
                    ,content: json.msg
                });
            }

        },
        error:function (result) {
            var json = JSON.parse(result);
            var layer = layui.layer;
            layer.open({
                title: '报错了'
                ,content: '更新失败'
            });

        }
    });
}




